package model

import (
	"errors"
	"ldaccount/pkg/util"
	"time"
)

const (
	// ChannelWechatMp 微信公众号
	ChannelWechatMp int8 = 1
	// ChannelWechatMina 微信小程序
	ChannelWechatMina int8 = 2
	// ChannelWecomSuite 企业微信应用
	ChannelWecomSuite int8 = 3
)

const (
	// ChannelWechatMpStr 微信公众号
	ChannelWechatMpStr string = "wechat_mp"
	// ChannelWechatMinaStr 微信小程序
	ChannelWechatMinaStr string = "wechat_mina"
	// ChannelWechatMinaStr 企业微信应用
	ChannelWecomSuiteStr string = "wecom_suite"
)

// LoginChannel 登陆渠道
type LoginChannel struct {
	// 增id
	Id int64 `json:"id" sql:"id"`
	// accounts id
	AccId int64 `json:"acc_id" sql:"acc_id"`
	// 平台 1~公众号 2~微信小程序
	Platform int8 `json:"platform" sql:"platform"`
	// 平台应用id
	AppId string `json:"app_id" sql:"app_id"`
	// 平台应用对应用户id
	OpenId string `json:"open_id" sql:"open_id"`
	// 平台应用对应用户唯一id
	UnionId string `json:"union_id" sql:"union_id"`
	// 昵称
	Nickname string `json:"nickname" sql:"nickname"`
	// 头像地址
	Avatar    string    `json:"avatar" sql:"avatar"`
	CreatedAt time.Time `json:"created_at" sql:"created_at"`
	UpdatedAt time.Time `json:"updated_at" sql:"updated_at"`
	DeletedAt int64     `json:"deleted_at" sql:"deleted_at"`
}

// NewLoginChannel 新建登陆渠道
func NewLoginChannel(accId int64, platform int8, appid, openid, unionid, nickname, avatar string) *LoginChannel {
	if !util.ContainInt8([]int8{
		ChannelWechatMp,
		ChannelWechatMina,
		ChannelWecomSuite,
	}, platform) {
		return nil
	}
	now := util.GetNow()
	return &LoginChannel{
		AccId:     accId,
		Platform:  platform,
		AppId:     appid,
		OpenId:    openid,
		UnionId:   unionid,
		Nickname:  nickname,
		Avatar:    avatar,
		CreatedAt: now,
		UpdatedAt: now,
	}
}

// SetPlatform 设置平台
func (l *LoginChannel) SetPlatform(plat, appid, openid, unionid string) error {
	switch plat {
	case ChannelWechatMpStr:
		l.Platform = ChannelWechatMp
	case ChannelWechatMinaStr:
		l.Platform = ChannelWechatMina
	case ChannelWecomSuiteStr:
		l.Platform = ChannelWecomSuite
	default:
		return errors.New("invalid login platform")
	}
	l.AppId = appid
	l.OpenId = openid
	l.UnionId = unionid
	l.UpdatedAt = util.GetNow()
	return nil
}

func GetInnerPlatform(plat string) (int8, error) {
	switch plat {
	case ChannelWechatMpStr:
		return ChannelWechatMp, nil
	case ChannelWechatMinaStr:
		return ChannelWechatMina, nil
	case ChannelWecomSuiteStr:
		return ChannelWecomSuite, nil
	default:
		return 0, errors.New("invalid login platform")
	}
}

// GetPlatform 获取平台
func (l *LoginChannel) GetPlatform() string {
	switch l.Platform {
	case ChannelWechatMp:
		return ChannelWechatMpStr
	case ChannelWechatMina:
		return ChannelWechatMinaStr
	case ChannelWecomSuite:
		return ChannelWecomSuiteStr
	default:
		return ""
	}
}

// UpdateChannel 更新渠道用户信息
func (l *LoginChannel) UpdateChannel(nickname, avatar string) {
	l.Nickname = nickname
	l.Avatar = avatar
	l.UpdatedAt = util.GetNow()
}

// Delete 删除渠道
func (l *LoginChannel) Delete() {
	l.DeletedAt = util.GetCurrentTimestamp()
}
